/*
 * @Author: 秦弘林 1092750452@qq.com
 * @Date: 2023-06-29 17:38:24
 * @LastEditors: 周浪 z13647966598@163.com
 * @LastEditTime: 2023-08-01 15:42:54
 * @FilePath: \printing-component\src\electron-service\mainMenu\index.js
 */
import { Menu, app, BrowserWindow } from 'electron'
import { getPrintersAsync } from '../ipc/index'
const { exec } = require('child_process')

/**
 * @method 生成mainMenu菜单
 */
export const mainMenu = (win, list) => {
  const menu = [
    {
      label: '工具',
      submenu: [
        {
          label: '退出',
          click: () => {
            console.log('退出')
            app.quit()
          },
        },
        {
          label: '重启',
          click: () => {
            app.relaunch()
            app.quit()
          },
        },
      ],
    },
    {
      label: '打印机',
      submenu: [
        {
          label: '打印首选项',
          id: 'print-preferences',
          submenu: list.map((m) => {
            return {
              label: m.name,
              click: () => {
                const platform = process.platform
                if (platform === 'win32') {
                  exec(`RUNDLL32 PRINTUI.DLL,PrintUIEntry /e /n "${m.name}"`)
                } else {
                  console.error('Opening printer preferences is not supported on this platform.')
                }
              },
            }
          }),
        },
        {
          label: '刷新打印机列表',
          click: () => {
            win.webContents.send('refreshPrintList', true)
          },
        },
      ],
    },
  ]
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    menu.push({
      label: '帮助',
      submenu: [
        {
          label: '调试',
          role: 'toggleDevTools',
          accelerator: 'F12',
        },
      ],
    })
  }
  return Menu.buildFromTemplate(menu)
}

/**
 * @method 初始化mainMenu菜单
 */
export const initMainMenu = (win, list) => {
  Menu.setApplicationMenu(mainMenu(win, list))
}
